<template>
	<view class="setting">
		<base-navbar back-color="#fff" title="系统设置"></base-navbar>
		<c-cell>
			<c-cell-item name="头像">
				<template #tips>
					<!-- #ifdef H5 || APP -->
					<button @click='changeAvatar' style="width: 100rpx;height: 100rpx;">
						<image :src="memberInfo.avatar" mode=""
							style="width: 100rpx;height: 100rpx;margin-left: -28rpx;"></image>
					</button>
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN -->
					<button open-type="chooseAvatar" @chooseavatar='onChooseAvatar'
						style="width: 100rpx;height: 100rpx;">
						<image :src="memberInfo.avatar" mode=""
							style="width: 100rpx;height: 100rpx;margin-left: -28rpx;"></image>
					</button>
					<!-- #endif -->
				</template>
			</c-cell-item>
			<c-cell-item name="修改昵称" :arrow="false">
				<template #tips>
					<input v-model="memberInfo.nickname" style="text-align: right;" type="nickname" @blur="blurname"
						placeholder="请输入昵称">
				</template>
			</c-cell-item>
			<c-cell-item name="修改手机号" :tips="memberInfo.mobile" @click="handleOpen"></c-cell-item>

			<!-- #ifdef APP -->
			<c-cell-item name="清除缓存" :tips="fileSizeString" @click="clearCache"></c-cell-item>
			<c-cell-item name="版本检查" :tips="'v '+version" @click="checkVersion"></c-cell-item>
			<c-cell-item name="权限设置" v-if="platform=='android'"
				@click="pageRoute('/pages/users/setting/permission?result=0')"></c-cell-item>
			<!-- #endif -->

			<c-cell-item name="账户注销" @click="pageRoute('/pages/users/setting/drop-account')"></c-cell-item>
			<c-cell-item name="退出登录" @click="handLoginOut"></c-cell-item>
		</c-cell>

		<view class="btn-submit" @click="save">
			<c-button type="error" block round>提交保存</c-button>
		</view>

		<!-- 修改手机号 -->
		<update-phone ref="popupRef" title="修改手机号"></update-phone>

		<app-update ref="appUpdate" :tabbar="true"></app-update>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import checkLogin from '@/utils/login';
	import {
		ref,
		reactive,
		toRefs,
		inject
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const web_host = inject('web_host');

	const state = reactive({
		memberInfo: [],
		form: {
			mobile: undefined,
			verify_code: undefined
		},
		tips: '获取验证码',
		countdown: 120, // 初始倒计时时间为60秒
		canGetCode: true, // 是否能获取验证码
		timer: null,
		version: '1.0.0',
		fileSizeString: 0, //缓存大小
		clearLoading: false, //清除动画
		ios: 0,
		platform: '', //h5 android ios
	});

	onLoad((opt) => {
		//登录过期自动登录
		console.log('登录状态', checkLogin());
		if (!checkLogin()) {
			uni.showModal({
				title: '提示',
				content: '请先授权登录',
				success: function(res) {
					uni.reLaunch({
						url: "/pages/users/login/login"
					})
				}
			});
		} else {
			getMemberInfo();
		}
	})

	onShow(() => {
		// #ifdef APP-PLUS
		formatSize(); //计算缓存
		// #endif
	})

	function getMemberInfo() {
		request.get('member/getMemberInfo').then(res => {
			state.memberInfo = res.data;
		})
	}

	function changeAvatar() {
		uni.chooseImage({
			count: 1, // 默认9，设置图片的选择数量
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				const uploadTask = uni.uploadFile({
					url: web_host + '/api/common.uploadfile/upload', // 开发者服务器接口地址
					filePath: tempFilePaths[0], // 要上传文件资源的路径
					name: 'file', // 文件对应的 key
					formData: {
						'user': 'test'
					}, // 请求的 form data
					success: (uploadFileRes) => {
						// console.log(uploadFileRes.data);
						const data = JSON.parse(uploadFileRes.data);
						console.log('上传成功', data);
						// 处理上传成功的结果
						uni.showToast({
							title: data.msg
						})
						if (data.status == 'done') {
							state.memberInfo.avatar = data.domainUrl;
						}
					},
					fail: (error) => {
						console.error('上传失败', error);
						// 处理上传失败的错误
						uni.showToast({
							title: '网络错误，请稍后再试！',
							icon: fail,
							duration: 2000
						})
					}
				});
				// 监听上传进度变化
				uploadTask.onProgressUpdate((res) => {
					console.log('上传进度' + res.progress);
				});
			},
			fail: (error) => {
				console.error('选择图片失败', error);
			}
		});
	}

	function onChooseAvatar(e) {
		uni.uploadFile({
			url: web_host + '/api/common.uploadfile/upload', // 开发者服务器接口地址
			filePath: tempFilePaths[0], // 要上传文件资源的路径
			name: 'file', // 文件对应的 key
			formData: {
				'user': 'test'
			}, // 请求的 form data
			success: (uploadFileRes) => {
				// console.log(uploadFileRes.data);
				const data = JSON.parse(uploadFileRes.data);
				console.log('上传成功', data);
				// 处理上传成功的结果
				uni.showToast({
					title: data.msg
				})
				if (data.status == 'done') {
					state.memberInfo.avatar = data.domainUrl;
				}
			},
			fail: (error) => {
				console.error('上传失败', error);
				// 处理上传失败的错误
				uni.showToast({
					title: '网络错误，请稍后再试！',
					icon: fail,
					duration: 2000
				})
			}
		});
	}

	function blurname(e) {
		state.memberInfo.nickname = e.detail.value;
	}

	function save() {
		request.post('member/upfield', {
			nickname: state.memberInfo.nickname,
			avatar: state.memberInfo.avatar,
		}).then(res => {
			console.log('修改会员信息', res);
			uni.showToast({
				title: res.msg
			})
		})
	}

	function getCode() {
		if (!state.form.mobile) {
			uni.showToast({
				title: '请输入手机号码',
				icon: "none"
			})
		} else {
			if (state.canGetCode) {
				// 向后端请求验证码
				state.canGetCode = false;
				uni.showLoading({
					title: '正在获取验证码'
				});
				request.post('common.sms/juheSend', {
					mobile: state.form.mobile
				}).then(res => {
					if (res.code == 1) {
						uni.hideLoading();
						uni.showToast({
							title: '验证码已发送'
						})
						// 开始倒计时
						startCountdown();
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				});
			} else {
				uni.showToast({
					title: '倒计时结束后再发送',
					icon: "none"
				})
			}
		}
	}

	function startCountdown() {
		if (state.timer) {
			return;
		}
		state.timer = setInterval(() => {
			if (state.countdown <= 0) {
				clearInterval(state.timer);
				state.countdown = 120;
				state.tips = '获取验证码';
				state.canGetCode = true;
				state.timer = null;
			} else {
				state.countdown -= 1;
				state.tips = state.countdown + ' S';
			}
		}, 1000);
	}

	function submit() {
		if (!state.form.mobile) {
			uni.showToast({
				title: '请输入手机号码',
				icon: "none"
			})
			return false;
		}
		updateMobile();
		/* if (!state.form.verify_code) {
			uni.showToast({
				title: '请输入验证码',
				icon: "none"
			})
			return false;
		}
		request.post('common.sms/checkcode', state.form).then(res => {
			if (res.code == 1) {
				updateMobile();
			} else {
				uni.showToast({
					title: res.msg,
					icon: "fail"
				})
			}
		}); */
	}

	function updateMobile() {
		request.post('member/upfield', {
			mobile: state.form.mobile,
		}).then(res => {
			console.log('修改手机号', res);
			state.memberInfo.mobile = state.form.mobile;
			uni.showToast({
				title: res.msg,
			})
			uni.navigateBack({
				delta: 1
			});
		})
	}

	//计算缓存大小方法
	function formatSize() {
		plus.cache.calculate(function(size) {
			let sizeCache = parseInt(size);
			if (sizeCache == 0) {
				state.fileSizeString = '0B';
			} else if (sizeCache < 1024) {
				state.fileSizeString = sizeCache + 'B';
			} else if (sizeCache < 1048576) {
				state.fileSizeString = (sizeCache / 1024).toFixed(2) + 'KB';
			} else if (sizeCache < 1073741824) {
				state.fileSizeString = (sizeCache / 1048576).toFixed(2) + 'MB';
			} else {
				state.fileSizeString = (sizeCache / 1073741824).toFixed(2) + 'GB';
			}
		})
	}

	// 清除缓存
	function clearCache() {
		state.clearLoading = true;
		let os = plus.os.name;
		if (os == 'Android') {
			let main = plus.android.runtimeMainActivity();
			let sdRoot = main.getCacheDir();
			let files = plus.android.invoke(sdRoot, 'listFiles');
			let len = files.length;
			for (let i = 0; i < len; i++) {
				let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径
				plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
					if (entry.isDirectory) {
						entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录
							uni.showToast({
								title: '缓存清理完成',
								duration: 2000,
								icon: 'none'
							});
							state.clearLoading = false;
							formatSize(); // 重新计算缓存
						}, function(e) {
							console.log(e.message);
						})
					} else {
						entry.remove();
					}
				}, function(e) {
					console.log('文件路径读取失败');
				})
			}
		} else {
			// ios暂时未找到清理缓存的方法，以下是官方提供的方法，但是无效，会报错
			plus.cache.clear(function() {
				state.clearLoading = false;
				formatSize();
			})
		}
	}

	function checkVersion() {
		console.log("版本检查");
		// #ifdef H5
		uni.showToast({
			title: '已是最新版本',
			duration: 2200,
			icon: 'none'
		});
		// #endif

		// #ifdef APP-PLUS
		uni.getSystemInfo({
			success: (res) => {
				if (res.platform == 'android') {
					plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { //获取版本号
						checkVersionOnAndroid(wgtinfo.version);
					})
				}
			}
		})
		// #endif
	}

	const appUpdate = ref(null);
	const popupRef = ref(null);

	//Android平台检查更新
	function checkVersionOnAndroid(version) {
		request.get('index/getAppVersion', {
			version: version
		}).then(res => {
			console.log('获取更新', res);
			if (res.code === 1) {
				if (res.data.isUpdate) {
					appUpdate.value.open();
				} else {
					uni.showToast({
						title: '已是最新版本',
						icon: 'none'
					})
				}
			}
		})
	}

	function handleOpen() {
		popupRef.value.open();
	}

	// 退出登录
	function handLoginOut() {
		uni.showModal({
			title: '确认退出登录',
			content: '是否要退出登录？',
			success: function(res) {
				if (res.confirm) {
					// console.log('用户点击确定');
					cache.logOut();

					pageRoute('/pages/init/init');
				} else if (res.cancel) {
					// console.log('用户点击取消');
				}
			}
		})
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	const {
		memberInfo,
		form,
		tips,
		countdown,
		canGetCode,
		timer,
		version,
		fileSizeString,
		clearLoading,
		ios,
		platform,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background-color: $bg-inverse-color;
	}

	.setting {
		.avatar {
			width: 80rpx;
			height: 80rpx;
			background-color: $bg-color;
			border-radius: $radius-circle;
		}

		.nickname {
			text-align: right;
		}

		.btn-submit {
			margin-top: 64rpx;
			padding: $margin-24;
		}
	}

	.phone-popup {
		padding: $margin-24;

		.form-item {
			@include f-between;
			padding: $margin-24 0;
			border-bottom: 1rpx solid mix($white-color, $border-color, 35%);

			.label {
				width: 120rpx;
			}

			.form-input {
				@include f-between;
				flex: 1;

				.value {
					flex: 1;
					padding: 0 $margin-12;
				}

				.code {
					font-size: $font-24;
					color: $primary-color;
				}
			}
		}

		:deep(.c-button) {
			margin-top: $margin-24;
		}
	}
</style>